import { createApp, h } from 'vue'
import ConfirmDialog from '../components/ConfirmDialog.vue'

export function showConfirm(options = {}) {
    return new Promise((resolve, reject) => {
        const container = document.createElement('div')

        const app = createApp({
            setup() {
                const destroy = () => {
                    app.unmount()
                    container.remove()
                }

                const handleConfirm = () => {
                    destroy()
                    resolve(true)
                }

                const handleCancel = () => {
                    destroy()
                    resolve(false)
                }

                return () =>
                    h(ConfirmDialog, {
                        visible: true,
                        'onUpdate:visible': val => {
                            if (!val) handleCancel()
                        },
                        onConfirm: handleConfirm,
                        onCancel: handleCancel,
                        ...options
                    })
            }
        })

        document.body.appendChild(container)
        app.mount(container)
    })
}
